<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Event
 *
 * @author adrian
 */
class Event {

    /**
     *
     * @var string
     */
    protected static $_events ;
    /**
     *
     * @var array
     */
    protected static $_has_run;
    /**
     *
     * @var mixed
     */
    protected static $_data;

    /**
     *
     * @param string $name
     * @param mixed $data
     */
    public static function run($name, & $data = NULL) {
        if (!empty(Event::$_events[$name])) {
            Event::$_data = & $data;
            $callbacks = Event::get($name);
            foreach ($callbacks as $callback) {
                call_user_func_array($callback, array(&$data));
            }
            $clear_data = '';
            Event::$_data = & $clear_data;
        }
        Event::$_has_run[$name] = $name;
    }

    /**
     *
     * @param string $name
     * @param mixed $callback
     * @param boolean $unique
     * @return boolean
     */
    public static function add($name, $callback, $unique = FALSE) {
        if (!isset(Event::$_events[$name])) {
            // Create an empty event if it is not yet defined
            Event::$_events[$name] = array();
        } elseif ($unique AND in_array($callback, Event::$_events[$name], TRUE)) {
            // The event already exists
            return FALSE;
        }
        Event::$_events[$name][] = $callback;
        return TRUE;
    }

    /**
     * Get all callbacks for an event.
     *
     * @param   string  event name
     * @return  array
     */
    public static function get($name) {
        return empty(Event::$_events[$name]) ? array() : Event::$_events[$name];
    }

}
?>
